package webapp.my.com.retrofit2okhttprjavademo.API;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import webapp.my.com.retrofit2okhttprjavademo.Bean.TokenBean;

/**
 * Created by ${Andy.li} on 2017/5/3.
 */

public class ApiModel {
    //服务器路径
    private static final String API_SERVER = "http://ncxlt.zpftech.com";
    private static Retrofit mRetrofit;
    private static OkHttpClient mOkHttpClient;
    public static ApiService apiservice = getRetrofit().create(ApiService.class);

    /**
     * 获取Retrofit对象
     *
     * @return
     */
    protected static Retrofit getRetrofit() {
        if (null == mRetrofit) {
            if (null == mOkHttpClient) {
                mOkHttpClient = OkHttp3Utils.getOkHttpClient();
            }
            //Retrofit2后使用build设计模式
            mRetrofit = new Retrofit.Builder()
                    //设置服务器路径
                    .baseUrl(API_SERVER + "/")
                    //添加转化库，默认是Gson
                    .addConverterFactory(GsonConverterFactory.create())
                    //添加回调库，采用RxJava
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    //设置使用okhttp网络请求
                    .client(mOkHttpClient)
                    .build();
        }
        return mRetrofit;
    }
    /**
     * 插入观察者
     *
     * @param observable
     * @param observer
     * @param <T>
     */
    public static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())//子线程访问网络
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(observer);
    }
    //POST请求
    public static void getToken(String appid, String appsecret, Observer<TokenBean> observer) {
        setSubscribe(apiservice.GetToken(appid, appsecret), observer);
    }
    //POST请求
    public static void getToken_string1(String appid, String appsecret, Observer<TokenBean> observer) {
        setSubscribe(apiservice.GetToken_String(appid, appsecret), observer);
    }
    //POST请求
    public static void getToken_string(Map<String,String> map, Observer<TokenBean> observer) {
        setSubscribe(apiservice.GetToken_String(map), observer);
    }

}
